package wechat

import (
	"context"
	"crypto/sha1"
	"encoding/hex"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/errors"
	"sort"
	"strconv"
	"strings"

	"gitee.com/Cauchy_AQ/vxopen/api/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type VerifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewVerifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VerifyLogic {
	return &VerifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *VerifyLogic) Verify(req *types.VerifyReq) (resp int64, err error) {
	err = verifySignatureSha1(req.Timestamp, req.Nonce, req.Signature)
	if err != nil {
		return 0, err
	}
	echo, _ := strconv.Atoi(req.Echostr)
	return int64(echo), nil
}

// verifySignatureSha1 校验 signature
func verifySignatureSha1(timestamp, nonce string, signature string) error {
	arr := []string{timestamp, nonce, "vxtoken"}
	sort.Strings(arr)
	h := sha1.New()
	h.Write([]byte(strings.Join(arr, "")))
	sha1Str := hex.EncodeToString(h.Sum(nil))
	if sha1Str != signature {
		return errors.ErrorVerifySignature
	}
	return nil
}
